<template>
  <div>
    <div class="user-info-head" @click="() => (open = true)">
      <img v-bind:src="store.avatar" title="点击上传头像" class="user-avatar" />
    </div>
    <el-dialog
      title="修改头像"
      v-model="open"
      width="800px"
      append-to-body
      @opened="modalOpened"
      @close="closeDialog"
    >
      <el-row>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="visible"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <div class="previewImg" :style="getStyle">
            <div :style="previewFileStyle">
              <img :src="previews.url" alt="" :style="previews.img" />
            </div>
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :sm="3" :xs="3">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button size="small" plain
              >选择图片
              <el-icon><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{ span: 1, offset: 2 }" :sm="2" :xs="2">
          <el-button
            :icon="Plus"
            size="small"
            @click="changeScale(1)"
          ></el-button>
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :sm="2" :xs="2">
          <el-button
            :icon="Minus"
            size="small"
            @click="changeScale(-1)"
          ></el-button>
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :sm="2" :xs="2">
          <el-button
            :icon="RefreshLeft"
            size="small"
            @click="rotateLeft()"
          ></el-button>
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :sm="2" :xs="2">
          <el-button
            :icon="RefreshRight"
            size="small"
            @click="rotateRight()"
          ></el-button>
        </el-col>
        <el-col :lg="{ span: 2, offset: 6 }" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadImg()"
            >提交</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 模块引入
import { reactive, ref, getCurrentInstance, nextTick } from 'vue'
import { VueCropper } from 'vue-cropper'
import 'vue-cropper/dist/index.css'
import {
  Plus,
  Minus,
  RefreshLeft,
  RefreshRight,
  Upload
} from '@element-plus/icons-vue'
import { ElMessageBox, ElNotification } from 'element-plus'
// import useLoginStore from '@/store/login'
import { uploadAvatarApi } from '@/api'
import useLoginStore from '@/store/login'

defineOptions({
  // 组件名称
  name: 'AvatarEdit',
  // 继承透传，是否继承没在子组件声明的父组件的属性
  inheritAttrs: true
})

const store = useLoginStore()
const { proxy } = getCurrentInstance() as any

const open = ref<boolean>(false) // 是否显示弹出层
const visible = ref<boolean>(false) // 是否显示cropper
const previews = ref<any>({}) // 预览数据
const previewFileStyle = ref<any>({}) // 预览样式
const cropper = ref()
const getStyle = ref<{
  width: number | string
  height: number | string
}>({
  width: '200px',
  height: '200px'
}) // 预览样式
const tempScale = ref<number>(0)
const options = reactive<{
  img: any
  autoCrop: boolean
  autoCropWidth: number
  autoCropHeight: number
  fixedBox: boolean
  outputType: string
  filename: string
}>({
  img: '', //裁剪图片的地址
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 200, // 默认生成截图框宽度
  autoCropHeight: 200, // 默认生成截图框高度
  fixedBox: true, // 固定截图框大小 不允许改变
  outputType: 'png', // 默认生成截图为PNG格式
  filename: 'avatar' // 文件名称
})
// const previewsRef = useTemplateRef<HTMLElement>('previewsRef')

const realTime = (data: any) => {
  previews.value = data
  // console.log(data)
  tempScale.value = options.autoCropWidth / data.w
  previewFileStyle.value = {
    width: data.w + 'px',
    height: data.h + 'px',
    margin: 0,
    overflow: 'hidden',
    zoom: tempScale.value,
    position: 'relative',
    border: '1px solid #e8e8e8',
    'border-radius': '2px'
  }
}

const modalOpened = () => {
  nextTick(() => {
    visible.value = true
  })
}
const closeDialog = () => {
  options.img = 'store.getters.avatar'
  visible.value = false
}

const changeScale = (num: number) => {
  num = num || 1
  proxy.$refs.cropper.changeScale(num)
}

const rotateLeft = () => {
  proxy.$refs.cropper.rotateLeft()
}

const rotateRight = () => {
  proxy.$refs.cropper.rotateRight()
}

const requestUpload = () => {}

const beforeUpload = (file: any) => {
  if (file.type.indexOf('image/') === -1) {
    ElNotification.error('文件格式错误，请上传图片类型文件')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElNotification.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    options.img = reader.result
    options.filename = file.name
  }
  return true
}

const uploadImg = () => {
  ElMessageBox.confirm('确定上传修改头像吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    //上传头像并且点击了确认按钮
    cropper.value.getCropBlob(async (data: any) => {
      // do something
      let formData = new FormData()
      //第三个参数是规定以什么为后缀，接口是根据后缀来返回地址格式的
      formData.append('file', data, 'avatar.jpg')
      formData.append('userId', store.userInfo?._id ?? '')
      //上传文件接口
      uploadAvatarApi(formData).then((res) => {
        console.log(res)
        ElNotification.success({
          title: '上传图像',
          message: '恭喜您上传更新头像成功！'
        })
        open.value = false
      })
    })
  })
}

// 压缩图片
// function compress(img: HTMLImageElement) {
//   let canvas = document.createElement('canvas')
//   let ctx = canvas.getContext('2d') as CanvasRenderingContext2D
//   // let initSize = img.src.length;
//   let width = img.width
//   let height = img.height
//   canvas.width = width
//   canvas.height = height
//   // 铺底色
//   ctx.fillStyle = '#fff'
//   ctx.fillRect(0, 0, canvas.width, canvas.height)
//   ctx.drawImage(img, 0, 0, width, height)
//   // 进行压缩
//   let ndata = canvas.toDataURL('image/jpeg', 0.8)
//   return ndata
// }
</script>

<style scoped lang="scss">
.user-info-head {
  position: relative;
  display: inline-block;
  height: 120px;
  &:hover {
    &::after {
      content: '+';
      position: absolute;
      inset: 0;
      font-size: 24px;
      font-style: normal;
      color: #eee;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
      line-height: 110px;
      border-radius: 50%;
      --webkit-font-smoothing: antialiased;
      box-sizing: border-box;
    }
  }
  .user-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    line-height: 110px;
    text-align: left;
    border: 2px solid #ccc;
  }
  :global(.show-preview) {
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
    overflow: hidden;
    border: 2px solid #f0f0f0;
    box-shadow: 0 0 4px #ccc;
  }
}
</style>
